package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;

import com.lehecai.core.exception.UnsupportedFetcherTypeException;
import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDrawPrizeItem;
import com.lehecai.core.lottery.fetcher.lotterydraw.impl.BaseLotteryDrawFetcher;
import com.lehecai.core.lottery.fetcher.lotterydraw.impl.LotteryDrawFetcher549;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;

/**
 * 海南体彩网 开奖结果抓取
 * 主要抓取海南4+1  <br/>
 * 历史地址:  http://www.tc.hainan.net/zq.asp?tctype=1   <br/>
 *
 * @author
 */
public class LotteryDrawFetch549WorkerOfficial extends AbstractLotteryDrawFetchWorker {

    public LotteryDrawFetch549WorkerOfficial() {
        super(LotteryType.A_HN4);
    }

    protected String siteName = "海南体彩网";
    protected String lotteryScope = "海南4+1";

    @Override
    public LotteryDraw fetchResult(String phase) {
        return null;
    }

    @Override
    public LotteryDraw fetchResultDetail(String phase) {
        LotteryType lotteryType = this.getLotteryType();

        String url = this.getResultDetailUrl(phase);
        if (url == null || url.isEmpty()) {
            logger.error("==" + lotteryScope + "==" + siteName + "==详细页面==抓取=="
                    + getLotteryType().getName() + "==期号：" + phase
                    + "==详细地址不存在，返回null");
            return null;
        }

        String pageInfo = "详细页面" + url;
        String encoding = "GBK";
        String logHeader = "==" + lotteryScope + "==" + siteName + "=="
                + pageInfo + "==抓取==" + getLotteryType().getName() + "==";
        logger.info(logHeader + "开始==");
        LotteryDraw lotteryDraw = new LotteryDraw();

        String data = null;

        try {
            data = CoreFetcherUtils.URLGet(url, null, encoding);
        } catch (Exception e) {
            logger.error("获取html数据失败" + e.getMessage());
            return null;
        }

        if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
            logger.error(logHeader + "data is null or 404 Not Found");
            return null;
        }

        //彩期
        String strPhase = StringUtils.substringBetween(data, "第", "期");
        //结果
        String strResult = StringUtils.replace(StringUtils.substringBetween(data, "开奖结果：", "<br"), "+", ",");
        //开奖日期
        String strTime = StringUtils.substringBetween(data, "开奖日：", "，");
        //销售额
        String strSales = StringUtils.substringBetween(data, "总销售额：", "元");

        String resultDetailStr = StringUtils.substringAfterLast(data, "========");

        List<LotteryDrawPrizeItem> resultDetail = new ArrayList<LotteryDrawPrizeItem>();

        String[] resultDetailArr = StringUtils.splitByWholeSeparator(resultDetailStr, "<br>");
        for (int i = 1; i < resultDetailArr.length; i++) {
            String[] vals = StringUtils.split(resultDetailArr[i], " ");
            if (vals.length < 3) {
                continue;
            }

            LotteryDrawPrizeItem prizeItem = new LotteryDrawPrizeItem();
            prizeItem.setName(vals[0]);
            prizeItem.setPrizeAmount(StringUtils.substringBefore(vals[2], "元"));
            prizeItem.setWinningCount(StringUtils.substringBefore(vals[1], "注"));

            resultDetail.add(prizeItem);
        }

        //set lotteryDraw
        lotteryDraw.setResultDetail(resultDetail);
        //判断彩期是否一致
        if (phase != null && !"".equals(phase)) {
            if (strPhase.equals(phase)) {
                lotteryDraw.setPhase(strPhase);
            } else {
                logger.error("要抓取的数据与指定彩期不匹配, fetchedPhase={}, phase={}", strPhase, phase);
                return null;
            }
        } else {
            lotteryDraw.setPhase(strPhase);
        }
        lotteryDraw.setLotteryType(lotteryType);
        lotteryDraw.setResult(strResult);
        lotteryDraw.setTimeDraw(strTime + " 00:00:00");
        lotteryDraw.setVolumeOfSales(strSales);

        logger.info(logHeader + lotteryDraw.getLotteryOpenResultLogMsg());

        return lotteryDraw;
    }

    @Override
    protected String getResultDetailUrl(String phase) {
        String toFetchPhase = phase;
        if (toFetchPhase == null || toFetchPhase.trim().length() == 0) {
            logger.info("未指定彩期，从首页获取最新开奖详情地址");
            // 获取最新期
            String encoding = CharsetConstant.CHARSET_UTF8;
            String data = null;

            try {
                data = CoreFetcherUtils.URLGet("http://tc.hainan.net/41/list_1.shtml", null, encoding);
            } catch (Exception e) {
                logger.error("获取html数据失败" + e.getMessage(), e);
            }
            if (data == null || data.indexOf("404 Not Found") > 0) {
                logger.error("抓取列表页面内容出错");
                return null;
            }

            Parser parser = null;
            try {
                parser = Parser.createParser(data, encoding);
            } catch (Exception e) {
                logger.error("解析html出错, data={}", data);
                return null;
            }

            try {
                TagNameFilter selectTagFileter = new TagNameFilter("select");
                NodeList selectNodeList = parser.extractAllNodesThatMatch(selectTagFileter);

                if (selectNodeList.size() > 0) {
                    parser.setInputHTML(selectNodeList.elementAt(0).toHtml());
                    TagNameFilter optionTagFileter = new TagNameFilter("option");
                    NodeList optionNodeList = parser.extractAllNodesThatMatch(optionTagFileter);
                    if (optionNodeList.size() > 0) {
                        TagNode tagNode = new TagNode();
                        tagNode.setText(optionNodeList.elementAt(0).toHtml());
                        toFetchPhase = tagNode.getAttribute("value");
                    }
                }
            } catch (Exception e) {
                logger.error("解析html出错" + e.getMessage(), e);
            }
        }
        if (toFetchPhase != null) {
            return "http://tycp.hainan.net/query.jsp?type=1&qh=" + toFetchPhase;
        }
        return null;
    }

    @Override
    protected String getResultUrl(String phase) {
        return null;
    }

    public static void main(String[] args) {
        BaseLotteryDrawFetcher fetcher = new LotteryDrawFetcher549();
        LotteryDraw lotteryDraw = null;
        try {
            lotteryDraw = fetcher.fetch(null);
        } catch (UnsupportedFetcherTypeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(lotteryDraw.getLotteryOpenResultLogMsg());
    }

}
